#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
vector<int> get_map(vector<vector<int>> map_index,vector<int> vector_index){
    vector<int> score(26, 1);
    for (int i = 0; i < vector_index.size();++i){
        score[vector_index[i]] = 0;
    }
    bool flag = true;
    while(flag){
        flag = false;
        for (int i = 0; i < map_index.size();++i){
            int temp1 = map_index[i][0];
            int temp2 = map_index[i][1];
            if (score[temp1]!=0&&score[temp2]==0){
                score[temp2] = score[temp1]+1;
                map_index.erase(map_index.begin() + i);
                flag = true;
            }
        }

    }
    return score;
}
int get_n(string temp,vector<int> score){
    int temp_score = 0;
    for (int i = 0; i < temp.size();++i){
        int temp_i = temp[i] - 97;
        if (score[temp_i]==0)
            return -1;
        temp_score += score[temp_i];
    }
    return temp_score;
}
int main()
{
    fstream fcin("test/2.txt");
    int n = 0;
    fcin >> n;
    for (int i = 0; i < n;++i){
        vector<vector<int>> map_index;
        int m = 0;
        fcin >> m;
        for (int j = 0; j < m;++j){
            char temp1, temp2;
            fcin >> temp1 >> temp2;
            vector<int> temp;
            temp.push_back(temp1 - 97);
            temp.push_back(temp2 - 97);
            map_index.push_back(temp);
        }
        fcin >> m;
        vector<int> vector_index;
        for (int j = 0; j < m;++j){
            char temp;
            fcin >> temp;
            vector_index.push_back(temp-97);
        }
        vector<int> score = get_map(map_index, vector_index);
        string temp;
        fcin >> temp;
        cout << get_n(temp, score);
    }

    fcin.close();
}